﻿using CHSystemApi.DataAccess.Entities;
using CHSystemApi.Framework.AuthServices;
using CHSystemApi.Framework.Base;
using CHSystemApi.Framework.Extension;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CHSystemApi.Business.implement
{
    public class PermissionService : IPermissionService
    {
        IServiceProvider _serviceProvider;

        IPermissionBusiness _business;

        internal List<PermissionContent> rules { get; private set; }

        public PermissionService(IServiceProvider serviceProvider, IPermissionBusiness business)
        {
            _serviceProvider = serviceProvider;
            _business = business;
        }

        public T ValidatePermission<T>(List<PermissionContent> validates) where T : IValidate
        {
            if (rules is null || rules.Count == 0)
                throw new BaseException(StatusCode.InsufficientPermissions, "权限不足，访问被拒绝！");
            foreach (PermissionContent item in validates)
            {
                if (rules.Where(x => x.Type == item.Type && x.Content.ToLower() == item.Content.ToLower()).Count() == 0)
                    throw new BaseException(StatusCode.InsufficientPermissions, "权限不足，访问被拒绝！");
            }
            return _serviceProvider.GetService<T>();
        }

        public IPermissionService SetRules(int userid)
        {
            rules = new List<PermissionContent>();
            Permission[] permissions = _business.GetPermissionsByUserid(userid);
            foreach (Permission item in permissions)
            {
                rules.Add(new PermissionContent() { Type = item.type, Content = item.rule });
            }
            return this;
        }
    }
}
